package cn.tedu.csmall.product.web;

import cn.tedu.csmall.product.exception.ServiceException;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;

/**
 * JsonResult
 *
 * @author chen
 * @since 2022/12/30 9:43:43
 */
@Data
public class JsonResult<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = -652905606210632153L;
    /**
     * 操作结果的状态码
     */
    @Schema(description = "业务状态码")
    private Integer state;
    /**
     * 操作“失败”时响应的提示文本
     */
    @Schema(description = "消息")
    private String message;
    /**
     * 操作“成功”时返回的数据
     */
    @Schema(description = "数据")
    private T data;

    public static <T> JsonResult<T> ok() {
        return ok(null);
    }

    public static <T> JsonResult<T> ok(T data) {
        JsonResult<T> jsonResult = new JsonResult<>();
        jsonResult.setState(ServiceCode.OK.getValue());
        jsonResult.setData(data);
        return jsonResult;
    }

    public static JsonResult<Void> fail(ServiceCode state, String message) {
        JsonResult<Void> jsonResult = new JsonResult<>();
        jsonResult.setState(state.getValue());
        jsonResult.setMessage(message);
        return jsonResult;
    }

    public static JsonResult<Void> fail(ServiceException e) {
        return fail(e.getServiceCode(), e.getMessage());
    }
}
